package clientServlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import validate.Validate;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PhoneNumber;

import controller.Controller;

@SuppressWarnings("serial")
public class NewOrderClient extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
	}


	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		// TODO Auto-generated method stub
		try{
			int orderID = Integer.parseInt(req.getParameter("orderID"));
			String bizUserName = req.getParameter("businessName");
			String phone = req.getParameter("phone");
			System.out.println("!!!!!! "+orderID+" "+bizUserName);

			if (Validate.phoneValid(phone))
			{
				String newPhone = phone.replaceAll("-", "");
				
				String userNameClient = (String) req.getSession().getAttribute("userNameClient");		

				String statusNotification = req.getParameter("statusNotification");
				String messageNotification = req.getParameter("messageNotification");

				boolean statusNotificationBoolean = false;
				boolean messageNotificationBoolean = false;

				if (statusNotification!=null && statusNotification.equals("on"))
					statusNotificationBoolean = true;

				if (messageNotification!=null && messageNotification.equals("on"))
					messageNotificationBoolean = true;

				int result = Controller.getInstance().addOrderToClient(userNameClient,bizUserName, orderID,newPhone, statusNotificationBoolean, messageNotificationBoolean);
				System.out.println("!@#!@#!@#!@#!@# "+ result);

				switch(result)
				{
				case 0:
					req.getSession().removeAttribute("validErrorClientNewOrder");
					resp.sendRedirect("/allClientOrders.jsp");
					break;
				case 1:
					req.getSession().setAttribute("validErrorClientNewOrder","business not exist");	
					resp.sendRedirect("/allClientOrders.jsp");
					break;
				case 2:
					req.getSession().setAttribute("validErrorClientNewOrder","order not exist");
					resp.sendRedirect("/allClientOrders.jsp");
					break;
				case 3:
					req.getSession().setAttribute("validErrorClientNewOrder","client not exist");	
					resp.sendRedirect("/allClientOrders.jsp");
					break;
				case 4:					
					req.getSession().setAttribute("validErrorClientNewOrder","phone not match");	
					resp.sendRedirect("/allClientOrders.jsp");
					break;
				}
			}
			else
			{
				req.getSession().setAttribute("validErrorClientNewOrder","invalid phone format");	
				resp.sendRedirect("/allClientOrders.jsp");
			}


		}
		catch(NumberFormatException e)
		{
			req.getSession().setAttribute("validErrorClientNewOrder","order id is not a number");	
			resp.sendRedirect("/allClientOrders.jsp");

		}


	}
}
